function Initialize()
	tables_exist()
end

function tables_exist()
	if (sql.TableExists("player_info") && sql.TableExists("player_skills") && sql.TableExists("player_exp")) then
		--Msg("Ignore this, unless its first time running gamemode\n")
	else
		if (!sql.TableExists("player_info")) then
			local query = "CREATE TABLE player_info ( unique_id varchar(255), money int, kills int, deaths int )"
			local result = sql.Query(query)
			if (sql.TableExists("player_info")) then
				Msg("Succes ! player_info table created \n")
			else
				Msg("Somthing went wrong with the player_info query ! \n")
				Msg( sql.LastError( result ) .. "\n" )
			end	
		end
		if (!sql.TableExists("player_skills")) then
			local query ="CREATE TABLE player_skills ( unique_id varchar(255), Mining int, Smithing int, Farming int, Cooking int, Woodcutting int, Carpentry int, Survival int, Technology int, Strength int, Health int )"
			local result = sql.Query(query)
			if (sql.TableExists("player_skills")) then
				Msg("Succes ! player_skill table created \n")
			else
				Msg("Somthing went wrong with the player_skills query ! \n")
				Msg( sql.LastError( result ) .. "\n" )
			end	
		end
		if (!sql.TableExists("player_exp")) then
			local query ="CREATE TABLE player_exp ( unique_id varchar(255), Mining int, Smithing int, Farming int, Cooking int, Woodcutting int, Carpentry int, Survival int, Technology int, Strength int, Health int )"
			local result = sql.Query(query)
			if (sql.TableExists("player_exp")) then
				Msg("Succes ! player_exp table created \n")
			else
				Msg("Somthing went wrong with the player_exp query ! \n")
				Msg( sql.LastError( result ) .. "\n" )
			end	
		end
	end
 
end

function SQLPlayerInitialSpawn(ply) -- saves stats every 300 seconds
		timer.Create(tostring(ply:SteamID()).."_delay", 1, 1,
		function()
			ply:SetNWString("SteamID", SteamID)
			timer.Create(tostring(ply:SteamID()).."_SaveStats", 300, 0, function() 
												ply:ChatPrint("Saving stats...")
												saveStats( ply ) 
												ply:ChatPrint("Stats saved !") end)
			player_exists( ply ) 
		end)
end

function player_exists ( ply )
	local steamID = ply:SteamID()
	local result = sql.Query("SELECT unique_id FROM player_info WHERE unique_id = '"..steamID.."'")
	if (result) then
		sql_value_stats( ply ) -- get stats
		sql_value_skills( ply ) -- get skills
		sql_value_exp(ply) -- get exp
	else
		new_player( steamID, ply ) -- Create a new player
	end

end
 
function new_player( SteamID, ply )
		sql.Query( "INSERT INTO player_info (`unique_id`, `money`, `kills`, `deaths`)VALUES ('"..SteamID.."', '0', '0', '0')" )
		local result = sql.Query( "SELECT unique_id FROM player_info WHERE unique_id = '"..SteamID.."'" )
		if (result) then
			sql.Query( "INSERT INTO player_skills (`unique_id`, `Mining`, `Smithing`, `Farming`, `Cooking`, `Woodcutting`, `Carpentry`, `Survival`, `Technology`, `Strength`, `Health`)VALUES ('"..SteamID.."', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1')" )
			result = sql.Query( "SELECT unique_id, Mining, Smithing, Farming, Cooking, Woodcutting, Carpentry, Survival, Technology, Strength, Health FROM player_skills WHERE unique_id = '"..SteamID.."'" )
			if (result) then
				sql.Query( "INSERT INTO player_exp (`unique_id`, `Mining`, `Smithing`, `Farming`, `Cooking`, `Woodcutting`, `Carpentry`, `Survival`, `Technology`, `Strength`, `Health`)VALUES ('"..SteamID.."', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0')" )
				result = sql.Query( "SELECT unique_id, Mining, Smithing, Farming, Cooking, Woodcutting, Carpentry, Survival, Technology, Strength, Health FROM player_skills WHERE unique_id = '"..SteamID.."'" )
				if (result) then
					Msg("Player account created !\n")
					sql_value_stats( ply )
					sql_value_skills( ply )
					sql_value_exp( ply )
				else
					Msg("Something went wrong with creating a players exp !\n")
				end				
			else
				Msg("Something went wrong with creating a players skills !\n")
			end
		else
			Msg("Something went wrong with creating a players info !")
		end
end

function sql_value_stats ( player )
	local steamID = player:SteamID()
	local money = sql.QueryValue("SELECT money FROM player_info WHERE unique_id = '"..steamID.."'")
	local kills = sql.QueryValue("SELECT kills FROM player_info WHERE unique_id = '"..steamID.."'")
	local deaths = sql.QueryValue("SELECT deaths FROM player_info WHERE unique_id = '"..steamID.."'")
	
	player:SetNWInt("money", money)
	player:SetNWInt("kills", kills)
	player:SetNWInt("deaths", deaths)
end
 
function sql_value_skills ( ply )
	local steamID = ply:SteamID()
	local Mining = sql.QueryValue("SELECT Mining FROM player_skills WHERE unique_id = '"..steamID.."'")
	local Smithing = sql.QueryValue("SELECT Smithing FROM player_skills WHERE unique_id = '"..steamID.."'")
	local Farming = sql.QueryValue("SELECT Farming FROM player_skills WHERE unique_id = '"..steamID.."'")
	local Cooking = sql.QueryValue("SELECT Cooking FROM player_skills WHERE unique_id = '"..steamID.."'")
	local Woodcutting = sql.QueryValue("SELECT Woodcutting FROM player_skills WHERE unique_id = '"..steamID.."'")
	local Carpentry = sql.QueryValue("SELECT Carpentry FROM player_skills WHERE unique_id = '"..steamID.."'")
	local Survival = sql.QueryValue("SELECT Survival FROM player_skills WHERE unique_id = '"..steamID.."'")
	local Technology = sql.QueryValue("SELECT Technology FROM player_skills WHERE unique_id = '"..steamID.."'")
	local Strength = sql.QueryValue("SELECT Strength FROM player_skills WHERE unique_id = '"..steamID.."'")
	local Health = sql.QueryValue("SELECT Health FROM player_skills WHERE unique_id = '"..steamID.."'")
	
	ply:SetNWInt("Mining", Mining)
	ply:SetNWInt("Smithing", Smithing)
	ply:SetNWInt("Farming", Farming)
	ply:SetNWInt("Cooking", Cooking)
	ply:SetNWInt("Woodcutting", Woodcutting)
	ply:SetNWInt("Carpentry", Carpentry)
	ply:SetNWInt("Survival", Survival)
	ply:SetNWInt("Technology", Technology)
	ply:SetNWInt("Strength", Strength)
	ply:SetNWInt("Health", Health)
end

function sql_value_exp ( ply )
	local steamID = ply:SteamID()
	local Mining = sql.QueryValue("SELECT Mining FROM player_exp WHERE unique_id = '"..steamID.."'")
	local Smithing = sql.QueryValue("SELECT Smithing FROM player_exp WHERE unique_id = '"..steamID.."'")
	local Farming = sql.QueryValue("SELECT Farming FROM player_exp WHERE unique_id = '"..steamID.."'")
	local Cooking = sql.QueryValue("SELECT Cooking FROM player_exp WHERE unique_id = '"..steamID.."'")
	local Woodcutting = sql.QueryValue("SELECT Woodcutting FROM player_exp WHERE unique_id = '"..steamID.."'")
	local Carpentry = sql.QueryValue("SELECT Carpentry FROM player_exp WHERE unique_id = '"..steamID.."'")
	local Survival = sql.QueryValue("SELECT Survival FROM player_exp WHERE unique_id = '"..steamID.."'")
	local Technology = sql.QueryValue("SELECT Technology FROM player_exp WHERE unique_id = '"..steamID.."'")
	local Strength = sql.QueryValue("SELECT Strength FROM player_exp WHERE unique_id = '"..steamID.."'")
	local Health = sql.QueryValue("SELECT Health FROM player_exp WHERE unique_id = '"..steamID.."'")
	
	ply:SetNWInt("MiningExp", Mining)
	ply:SetNWInt("SmithingExp", Smithing)
	ply:SetNWInt("FarmingExp", Farming)
	ply:SetNWInt("CookingExp", Cooking)
	ply:SetNWInt("WoodcuttingExp", Woodcutting)
	ply:SetNWInt("CarpentryExp", Carpentry)
	ply:SetNWInt("SurvivalExp", Survival)
	ply:SetNWInt("TechnologyExp", Technology)
	ply:SetNWInt("StrengthExp", Strength)
	ply:SetNWInt("HealthExp", Health)
end
 
function saveStats( ply )
	local money = ply:GetNWInt("money")
	local kills = ply:GetNWInt("kills")
	local deaths = ply:GetNWInt("deaths")
	local unique_id = ply:SteamID()
	local Mining = ply:GetNWInt("Mining")
	local Smithing = ply:GetNWInt("Smithing")
	local Farming = ply:GetNWInt("Farming")
	local Cooking = ply:GetNWInt("Cooking")
	local Woodcutting = ply:GetNWInt("Woodcutting")
	local Carpentry = ply:GetNWInt("Carpentry")
	local Survival = ply:GetNWInt("Survival")
	local Technology = ply:GetNWInt("Technology")
	local Strength = ply:GetNWInt("Strength")
	local Health = ply:GetNWInt("Health")
	
	local MiningEXP = ply:GetNWInt("MiningExp")
	local SmithingEXP = ply:GetNWInt("SmithingExp")
	local FarmingEXP = ply:GetNWInt("FarmingExp")
	local CookingEXP = ply:GetNWInt("CookingExp")
	local WoodcuttingEXP = ply:GetNWInt("WoodcuttingExp")
	local CarpentryEXP = ply:GetNWInt("CarpentryExp")
	local SurvivalEXP = ply:GetNWInt("SurvivalExp")
	local TechnologyEXP = ply:GetNWInt("TechnologyExp")
	local StrengthEXP = ply:GetNWInt("StrengthExp")
	local HealthEXP = ply:GetNWInt("HealthExp")

	sql.Query("UPDATE player_skills SET Mining = "..Mining..", Smithing = "..Smithing..", Farming = "..Farming..", Cooking = "..Cooking..", Woodcutting = "..Woodcutting..", Carpentry = "..Carpentry..", Survival = "..Survival..", Technology = "..Technology..", Strength = "..Strength..", Health = "..Health.." WHERE unique_id = '"..unique_id.."'")
	sql.Query("UPDATE player_info SET money = "..money..", kills = "..kills..", deaths = "..deaths.." WHERE unique_id = '"..unique_id.."'")
	sql.Query("UPDATE player_exp SET Mining = "..MiningEXP..", Smithing = "..SmithingEXP..", Farming = "..FarmingEXP..", Cooking = "..CookingEXP..", Woodcutting = "..WoodcuttingEXP..", Carpentry = "..CarpentryEXP..", Survival = "..SurvivalEXP..", Technology = "..TechnologyEXP..", Strength = "..StrengthEXP..", Health = "..HealthEXP.." WHERE unique_id = '"..unique_id.."'")
end

function SQLPlayerDisconnect( player )
	saveStats(player)
	timer.Destroy(tostring(player:SteamID()).."_delay")
	timer.Destroy(tostring(player:SteamID()).."_SaveStats")
end

hook.Add("PlayerInitialSpawn", "SQLPlayerInitialSpawn", SQLPlayerInitialSpawn)
hook.Add("Initialize", "Initialize", Initialize)
hook.Add( "PlayerDisconnected", "sqlplayerdisconnected", SQLPlayerDisconnect )
